<?php


namespace app\shop\controller;

use app\admin\controller\ApiCommon;

use app\crm\model\ProductItem;
use app\crm\model\ShopGoods;
use app\shop\model\MedicalRecordsOrder;
use app\shop\model\Order as OrderModel;
use app\shop\model\Refund;
use app\shop\model\Warehouse as WarehouseModel;
use Kingdee\Kingdee;
use think\facade\Db;
use think\response\Json;

/**
 * 订单类
 * @package app\shop\controller
 * @author SL
 * @create 2020-06-01
 */
class Order extends ApiCommon
{

    /**
     * 用于判断权限
     * @permission 无限制
     * @allow 登录用户可访问
     * @author SL
     * @create 2021-06-01
     */
    public function initialize()
    {

        $action = [
            'permission' => [''],
            'allow' => ['export']
        ];
        event('CheckAuth', $action);
        $request = $this->request;
        $a       = strtolower($request->action());
        if (!in_array($a, $action['permission'])) {
            parent::initialize();
        }
    }

	/*
	* 修改订单--销售出库单
	* @create 2022-04-19
	*/
	public function updateDetail()
	{
        $this->param['user_id'] = $this->userInfo['id'];
        $this->param['shop_id'] = $this->userInfo['shop_id'];
		$orderModel = new OrderModel();
	    $data       = $orderModel->updateDataDetail($this->param);

	    if (!$data) {
	        return resultArray(['error' => $orderModel->getError()]);
	    }

	    return resultArray(['data' => $data]);
	}

    /**
     * 订单列表
     * @return Json
     * @author SL
     * @create 2021-06-01
     */
    public function index(): Json
    {
        $header = request()->header();
        $this->param['platform'] = $header['platform'];
        $this->param['user_id'] = $this->userInfo['id'];
        $this->param['shopIds'] = $this->getCommonShopIdsCollectByUserType();
        $this->param['person_shop_id'] = $this->userInfo['shop_id'];
        $this->param['admin_user_id'] = $this->userInfo['shop_person_id'];

        $orderModel = new OrderModel();
        $data       = $orderModel->getDataList($this->param);
        if (!$data) {
            return resultArray(['error' => $orderModel->getError()]);
        }
        return resultArray(['data' => $data]);
    }

    /**
     * 订单主要详情
     * @return Json
     * @author SL
     * @create 2021-06-02
     */
    public function detail(): Json
    {
        $orderModel = new OrderModel();
        $data       = $orderModel->getDataDetail($this->param);
        if (!$data) {
            return resultArray(['error' => $orderModel->getError()]);
        }
        return resultArray(['data' => $data]);
    }

    /**
     * 订单商品详情
     * @return Json
     * @author SL
     * @create 2021-06-02
     */
    public function orderGoodsDetail(): Json
    {
        $orderModel = new OrderModel();
        $data       = $orderModel->getGoodsDataDetail($this->param);
        if (!$data) {
            return resultArray(['error' => $orderModel->getError()]);
        }
        return resultArray(['data' => $data]);
    }

    /**
     * 订单商品护理师及服务小项变更详情
     * @return Json
     * @author SL
     * @create 2021-06-02
     */
    public function orderGoodsOptionDetail(): Json
    {
        $orderModel = new OrderModel();
        $data       = $orderModel->orderGoodsOptionDetail($this->param);
        if (!$data) {
            return resultArray(['error' => $orderModel->getError()]);
        }
        return resultArray(['data' => $data]);
    }

    /**
     * 创建订单
     * @return Json
     * @author SL
     * @create 2021-06-03
     */
    public function create(): Json
    {
        $this->param['operator_id'] = $this->userInfo['id'];
        $this->param['operator_name'] = $this->userInfo['username'];
        $orderModel = new OrderModel();
        $data       = $orderModel->addData($this->param);
        if (!$data) {
            return resultArray(['error' => $orderModel->getError()]);
        }
        return resultArray(['data'=> [], 'error' => $orderModel->getError()]);
    }


    /**
     * 修改订单状态
     * @return Json
     * @author SL
     * @create 2021-06-08
     */
    public function checkOrder(): Json
    {
        $orderModel = new OrderModel();
        $this->param['operator_id'] = $this->userInfo['id'];
        $data          = $orderModel->checkOrderData($this->param);
        if (!$data) {
            return resultArray(['error' => $orderModel->getError()]);
        }
        return resultArray(['data'=> [], 'error' => $orderModel->getError()]);
    }

    /**
     * 锁单
     * @return Json
     * @author SL
     * @create 2021-06-08
     */
    public function lockOrder(): Json
    {
        $orderModel = new OrderModel();
        $this->param['operator_id'] = $this->userInfo['id'];
        $data          = $orderModel->lcokOrderData($this->param);
        if (!$data) {
            return resultArray(['error' => $orderModel->getError()]);
        }
        return resultArray(['data' => $data, 'error' => $orderModel->getError()]);
    }

    /**
     * 病例开单
     * @return Json
     * @author SL
     * @create 2021-06-10 9:31
     */
    public function caseCreateOrder(){

        $this->param['operator_id'] = $this->userInfo['id'];
        $this->param['operator_name'] = $this->userInfo['username'];
        $orderModel = new MedicalRecordsOrder();
        $data       = $orderModel->caseCreateOrder($this->param);
        if (!$data) {
            return resultArray(['error' => $orderModel->getError()]);
        }
        return resultArray(['data'=> [], 'error' => $orderModel->getError()]);

    }



     /**
     * 获取订单支付金额
     */
    public function caseGetPayment(): Json
    {

        try {
            $param = $this->param;
            // 设置返回数据
            $balanceType = [
                1=>[
                    'this' => 'zc_goods',
                    'all'  => 'zc_allgoods'
                ],
                2=>[
                    'this' => 'zc_fuwu',
                    'all'  => 'zc_allfuwu'
                ],
                3=>[
                    'this' => 'zc_fuwu',
                    'all'  => 'zc_allfuwu'
                ],
                4=>[
                    'this' => 'zc_fuwu',
                    'all'  => 'zc_allfuwu'
                ],
            ];
            $retuenData = [
                'zc_goods_y'    => '0.00', // 疤痕需要支付的余额
                'zc_goods_z'    => '0.00', // 疤痕需要支付的赠金
                'zc_allgoods_z' => '0.00', // 疤痕需要支付的总金额
                'zc_fuwu_y'     => '0.00', // 服务需要支付的余额
                'zc_fuwu_z'     => '0.00', // 服务需要支付的赠金
                'zc_allfuwu_z'  => '0.00',
                'yhj_list'      => [],
            ];

            //获取订单总金额
            $order_amout       = isset($param['order_amout']) ? $param['order_amout'] : 0;         // 订单总计
            $customer_id       = isset($param['customer_id']) ? intval($param['customer_id']) : 0; // 客户id
            $order_goods       = isset($param['goods']) ? $param['goods'] : []; // 订单商品
            if ($order_amout < 0) {
                throw new \Exception('订单金额异常，无法获取客户支付金额');
            }
            if(empty($order_goods)){
                throw new \Exception('无需出库商品');
            }
            // 如果订单金额为0，则直接返回数据
            if ($order_amout == 0) {
                return resultArray(['data' => $retuenData,'error'=>'获取成功']);
            }

            $refundModel = new Refund();
            list($benj,$zengj,$customerMoney) = $refundModel->customerBalanceVerify($customer_id);

            $cjyh = 0;
            $is_have_cjyh = $cjyh_arr = [];
            $is_have_goods = [];
            $project_arr = $product_project_arr = [];
            $project_ids = $product_ids = [];
            $productAmount = $projectAmount = [];
            $cjyh_bj = $cjyh_zj = [];
            $kcbj = $kczj = [];
            foreach ($order_goods as $key => $val) {

                if(!isset($val['number']) || empty($val['number'])) {
                    throw new \Exception("请填写销售数量");
                }
//                if(!isset($val['house_code']) || empty($val['house_code'])) {
//                    throw new \Exception("请选择仓库");
//                }

                if($val['id'] == 170) {
                    if ($val['pay_price'] < 0) {
                        throw new \Exception('冲减优惠不能为0');
                    }
                    $cjyh = bcmul($val['pay_price'], $val['number'], 2);
                    array_push($is_have_cjyh, 1);
                    array_push($cjyh_arr, $val);
                }

                if($val['prestock_type'] != 3 && $val['pay_price'] >0){

                    //关于商品的判断
                    if($val['goods_type'] == 2 && $val['id'] != 170){
                        //商品选择-才选择业务分类
                        if(!in_array($val['business_type'],[1,2,3,4])){
                            throw new \Exception('请选择项目分类');
                        }
                        array_push($is_have_goods,1);
                        array_push($product_project_arr,$val);
                        array_push($product_ids,$val['id']);
                        $productAmount[] = bcmul($val['pay_price'], $val['number'], 2);

                    }
                    //关于品项的判断
                    elseif ($val['goods_type'] == 1 ){
                        $projectAmount[] = bcmul($val['pay_price'], $val['number'], 2);
                        array_push($is_have_goods,1);
                        array_push($product_project_arr,$val);
                        array_push($project_ids,$val['id']);
                    }

                }
            }


            $is_have_cjyh_count = count($is_have_cjyh);
            if($is_have_cjyh_count >1){
                throw new \Exception('同一个单子不能出现两项冲减优惠');
            }else if ($is_have_cjyh_count >0 && empty($is_have_goods)){
                throw new \Exception('冲减优惠没有优惠商品');
            } else if($is_have_cjyh_count >0 && $cjyh == 0){
                throw new \Exception('冲减优惠不能等于零');
            }

            $productAmount = bcadd(0,array_sum($productAmount),2); //商品之和
            $projectAmount = bcadd(0,array_sum($projectAmount),2); //项目之和



            $total_amount = $productProjectAmount = bcadd($productAmount,$projectAmount,2); //优惠前的订单金额

            if($is_have_cjyh_count >0 && $total_amount < $cjyh){
                throw new \Exception('冲减优惠无法使用');
            }
            $shopGoods =[];
            if(!empty($product_ids)){
                $shopGoods = ShopGoods::whereIn('id', $product_ids)
                    ->where('status', 1)
                    ->column('name,category_id,kingdee_code,goods_price,spec_name,unit_code,unit_name,is_prestock', 'id');

            }
            $project = [];
            if(!empty($project_ids)){
                $project = ProductItem::whereIn('id',$project_ids)
                ->where('status',1)
                ->column('price,name,number,product_info,type_one,type_two,type_three','id');
            }

            $cjyh_bj = $cjyh_zj = [];
            $discount_amount_arr = [];//冲减优惠-商品优惠后的总金额
            $product_project_arr_count = count($product_project_arr);

            $customerModel = new \app\crm\model\Customer();

            foreach ($product_project_arr as $pk => &$pv) {

                if (!isset($shopGoods[$pv['id']]) && $pv['goods_type'] == 2 ) {
                    throw new \Exception('商品不存在');
                }

                if (!isset($project[$pv['id']]) && $pv['goods_type'] == 1 ) {
                    throw new \Exception('品项不存在');
                }

                $customerBalance['money'] = $benj;
                $customerBalance['complimentary_money'] = $zengj;

                $one_product_amount = bcmul($pv['pay_price'], $pv['number'], 2);

                $discount_amount = 0; //优惠金额
                if ($productProjectAmount > 0 && $cjyh != 0) {
                    //涉及到冲减优惠
                    if ($product_project_arr_count > 1 ) {
                        if ($pk + 1 == $product_project_arr_count) {
                            $discount_amount = bcsub($cjyh, bcadd(0, array_sum($discount_amount_arr), 2), 2); //最后一个优惠金额
                        } else {
                            $discount_amount = bcmul($cjyh, ($one_product_amount/$productProjectAmount), 2); //优惠金额
                        }
                    } else {

                        $discount_amount = bcmul($cjyh, ($one_product_amount/$productProjectAmount), 2); //优惠金额
                    }

                    $one_product_amount = bcadd($one_product_amount, $discount_amount, 2);
                }

                array_push($discount_amount_arr, $discount_amount);

                $customerBalance['actual_order_amout'] = $one_product_amount;
                $pay_money = $customerModel->getCustomerAmountConsumed($customerBalance); //获取订单消耗的本金、赠金、店转
                $bj = bcadd($pay_money['pay_benjin_amount'], 0, 2);  //单条优惠后的本金
                $zj = bcadd($pay_money['pay_zengjin_amount'], 0, 2); //单条优惠后的赠金
                //                    var_dump('优惠金额：'.$discount_amount);
                //                    var_dump('扣款本金：'.$bj.'扣款赠金'.$zj);
                array_push($kcbj, $bj);
                array_push($kczj, $zj);
            }

            $deduct_balance = bcadd(array_sum($kcbj),0,2);
            $deduct_gift    = bcadd(array_sum($kczj),0,2);
            $actual_order_amout = bcadd($deduct_balance,$deduct_gift,2);
            $business_type = 2;
            $retuenData[$balanceType[$business_type]['this'].'_y'] = $deduct_balance; //实际支付本金
            $retuenData[$balanceType[$business_type]['this'].'_z'] =  $deduct_gift;  //实际支付赠金
            // 设置支付总金额
            $retuenData[$balanceType[$business_type]['all'].'_z']  = $actual_order_amout; //实收总额

            return resultArray(['data' => $retuenData,'error'=>'获取成功']);
        }catch (\Exception $e){
            return resultArray(['error'=>$e->getMessage()]);
        }
    }

    /**
     * 病例开单-修改订单
     * @return Json
     * @author SL
     * @create 2021-06-10 9:31
     */
    public function caseUpdateOrder(){

        $this->param['operator_id'] = $this->userInfo['id'];
        $this->param['operator_name'] = $this->userInfo['username'];
        $orderModel = new MedicalRecordsOrder();
        $data       = $orderModel->caseUpdateOrder($this->param);
        if (!$data) {
            return resultArray(['error' => $orderModel->getError()]);
        }
        return resultArray(['data' => $data,'error'=>'操作成功']);
    }


    /**
     * 病例开单-病例订单列表
     * @return Json
     * @author SL
     * @create 2021-06-10 9:31
     */
    public function caseOrderList(){

        $this->param['operator_id'] = $this->userInfo['id'];
        $this->param['operator_name'] = $this->userInfo['username'];
        $orderModel = new MedicalRecordsOrder();
        $data       = $orderModel->caseOrderList($this->param);
        if (!$data) {
            return resultArray(['error' => $orderModel->getError()]);
        }
        return resultArray(['data'=> $data, 'error' => '获取成功']);
    }


    /**
     * 病例开单-病例订单取消
     * @return Json
     * @author SL
     * @create 2021-06-10 9:31
     */
    public function caseOrderCancel(){

        $this->param['operator_id'] = $this->userInfo['id'];
        $this->param['operator_name'] = $this->userInfo['username'];
        $orderModel = new MedicalRecordsOrder();
        $data       = $orderModel->caseOrderCancel($this->param);
        if (!$data) {
            return resultArray(['error' => $orderModel->getError()]);
        }
        return resultArray(['data' => $data,'error'=>'操作成功']);
    }

    /**
     * 病例开单-订单详情
     */
    public function caseOrderDetail(): Json
    {
        try {
            $orderModel = new MedicalRecordsOrder();
            $retuenData       = $orderModel->getOrderDetail($this->param);
            if (!$retuenData) {
                return resultArray(['error' => $orderModel->getError()]);
            }
            return resultArray(['data' => $retuenData,'error'=>'获取成功']);
        }catch (\Exception $e){
            return resultArray(['error'=>$e->getMessage()]);
        }
    }


    //获取顾客余额接口
    public function getCustomerAccount(){
        try {
            $orderModel = new MedicalRecordsOrder();
            $retuenData       = $orderModel->getCustomerAccount($this->param);
            if (!$retuenData) {
                return resultArray(['error' => $orderModel->getError()]);
            }
            return resultArray(['data' => $retuenData,'error'=>'获取成功']);
        }catch (\Exception $e){
            return resultArray(['error'=>$e->getMessage()]);
        }
    }




    /**
     * 订单操作记录
     * @return Json
     * @author SL
     * @create 2021-06-10 9:31
     */
    public function record(): Json
    {
        $this->param['user_id'] = $this->userInfo['id'];
        $orderModel = new orderModel();
        $data          = $orderModel->getOrderRecordList($this->param);
        if (!$data) {
            return resultArray(['error' => $orderModel->getError()]);
        }
        return resultArray(['data' => $data]);
    }



    /**
     * 销售政策列表
     * @return Json
     * @author LIU
     * @create 2021-10-27 9:31
     */
    public function saleList(): Json
    {
        $this->param['user_id'] = $this->userInfo['id'];
        $orderModel = new orderModel();
        $data          = $orderModel->getSaleList();
        if (!$data) {
            return resultArray(['error' => $orderModel->getError()]);
        }
        return resultArray(['data' => $data]);
    }


    /**
     * 仓库列表
     * @return Json
     * @author LIU
     * @create 2021-10-27 9:31
     */
    public function houseList(): Json
    {
        $orderModel = new orderModel();
        $data          = $orderModel->getHouseList($this->param);
        if (!$data) {
            return resultArray(['error' => $orderModel->getError()]);
        }
        return resultArray(['data' => $data]);
    }




    /**
     * 订单退款单
     *
     */
    public function refundMoney()
    {
        $order_id = $this->param['id'];
        $kingDee = new Kingdee();
        $res = $kingDee->refund_money($order_id);
    }


    /**
     * 订单退货单
     *
     */
    public function refundGoods()
    {
        $order_id = $this->param['id'];
        $kingDee = new Kingdee();
        $res = $kingDee->refund_goods($order_id);
    }


    /**
     * 推送会员
     *
     */
    public function pushCustomer()
    {
        $user_id = $this->param['id'];
        $kingDee = new Kingdee();
        $res = $kingDee->add_customer($user_id);//保存
        //$res = $kingDee->submit_customer($user_id);//提交
        //$res = $kingDee->audit_customer($user_id);//审核
        //$res = $kingDee->again_audit_customer($user_id);//反审核
    }


    /**
     * 收款单
     *
     */
    public function receiptMoney()
    {
        $order_id = $this->param['id'];
        $kingDee = new Kingdee();
        $res = $kingDee->receipt_money($order_id);
    }


    /**
     * 导出订单
     * @author Mr.Liu
     * @create 2021-06-09 10:46
     */
    public function export()
    {
        $requestId = isset($this->request['id']) && $this->request['id'] ? $this->request['id'] : [];
        if($requestId){
            $idArr = is_array($requestId) ? $requestId : explode(',', $requestId);
        }else{
            $idArr = [];
        }
        $orderModel = new orderModel();
        $data          = $orderModel->getDataList(['page' => 1,'limit' => 10000,'id' => $idArr]);

        if(empty($data['list'])){
            $data['list'] = [];
        }
        $callName = ['deal_time' =>'成交日期','consignee' =>'客户名称','king_no' =>'客户K3代码','shop_name' => '门店','sale_name' => '护理师','goods_price' => '标准金额','order_amount' => '销售金额','business_type' => '业务类型','order_type' => '订单类型'];
        $downUrl = exportExcelData('order',$callName,$data['list'],'xlsx',1);
        return resultArray(['data' =>['url' => 'http://'.$_SERVER['HTTP_HOST'].$downUrl],'error' => '获取成功']);
    }





    /**
     * 订单下推销售出库单
     *
     */
    public function orderPush()
    {
        $order_id = $this->param['id'];
        $user_id  = $this->userInfo['id'];
        // 查询订单信息 判断订单的支付状态
        $orderModel = new orderModel();
        $orderInfo = $orderModel->where('id', $order_id)->find();
        if ( !$orderInfo ) {
            return resultArray(['error'=> '订单信息获取失败']);
        }

        // 判断订单是否已下推
        if ($orderInfo['status'] >= 2) {
            return resultArray(['error'=> '该订单已下推']);
        }
        $customer= Db::name('customer')->where('id',$orderInfo['uid'])->field('king_no,king_status')->find();

        if (!$customer['king_no'] || !$customer['king_status'] == 2)
        {
            exit(json_encode(['code'=>404, 'data' => [], 'msg'=>'客户信息没有金蝶编码或者是禁用状态']));
        }

        $kingDee = new Kingdee();
        $res = $kingDee->send_order($order_id);
        if ($res['code']) {
            return resultArray(['error'=> $res['msg']]);
        }
        $orderModel = new OrderModel();
        $orderModel->addActionRecord($user_id, 'shop_order_check', $order_id, '订单已下推', 'shop', 'order');
        return resultArray(['data'=> [], 'error'=> '操作成功']);
    }

    /**
     * 获取销售订单数据
     *
     */
    public function getSaleOrder()
    {
        $order_id = $this->param['order_id'];
        $user_id  = $this->userInfo['id'];
        // 查询订单信息 判断订单的支付状态
        $orderModel = new orderModel();
        $orderInfo = $orderModel->where('id', $order_id)->find();
        if ( !$orderInfo ) {
            return resultArray(['error'=> '订单信息获取失败']);
        }

        // 判断客户是否确认订单
        if ($orderInfo['king_status'] != 1) {
            return resultArray(['error'=> '金蝶推送状态异常']);
        }

        // 金蝶销售出库单号
        if ( !$orderInfo['king_sale_no'] ) {
            return resultArray(['error'=> '金蝶销售出库单号为空']);
        }

        $kingDee = new Kingdee();
        $data = $kingDee->get_sale_order($orderInfo['king_sale_no']);
        return resultArray(['data'=> $data]);
    }

}

?>
